﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace UFramework.Tools
{
    public class Drag3D : MonoBehaviour
    {
        private float disCamForward;
        private new Camera camera;
        private Transform camTf;
        private void Start()
        {
            camera = Camera.main;
            camTf = camera.transform;
        }

        private void OnMouseDown()
        {
            StartCoroutine("Drag");
        }

        private IEnumerator Drag()
        {
            print("开始拖拽");
            StartDrag();
            while (true)
            {
                print("拖拽中");
                OnDraging();
                if (Input.GetMouseButtonUp(0)) EndDrag();
                yield return null;
            }
        }

        private void OnDraging()
        {
            Vector3 mouseDir = camera.ScreenPointToRay(Input.mousePosition).direction.normalized;
            float angleMouseDir = Vector3.Angle(camTf.forward, mouseDir);
            float disInMouseDir = disCamForward / Mathf.Cos(angleMouseDir * Mathf.Deg2Rad);
            transform.position = camTf.position + mouseDir * disInMouseDir;
        }

        private void StartDrag()
        {
            //计算投影到摄像机前方的点
            Vector3 camToGo = (transform.position - camTf.position);
            float camToGoDis = camToGo.magnitude;
            float angle = Vector3.Angle(camTf.forward, camToGo);
            disCamForward = camToGoDis * Mathf.Cos(Mathf.Deg2Rad * angle);
            // Debug.DrawRay(camTf.position, camTf.forward * disCanForward, Color.red, 20);
        }
        private void EndDrag()
        {
            StopCoroutine("Drag");
            print("结束拖拽");
        }
    }
}